#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import glob
import mrget
import shutil
import pathlib
import subprocess


class Util:

    @staticmethod
    def forceDelete(path):
        if os.path.islink(path):
            os.remove(path)
        elif os.path.isfile(path):
            os.remove(path)
        elif os.path.isdir(path):
            shutil.rmtree(path)
        elif os.path.lexists(path):
            os.remove(path)             # other type of file, such as device node
        else:
            pass                        # path does not exist, do nothing


selfDir = os.path.dirname(os.path.realpath(__file__))

repo = "vimproved-overlay"
repoDir = os.path.join(selfDir, repo)
url = mrget.target_urls("mirror://github/gentoo-mirror/vimproved", protocols=["http", "https", "ftp"], max_count=3)[0]
Util.forceDelete(repoDir)
subprocess.check_call(["git", "clone", url, repoDir], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

preEnableDir = os.path.join(selfDir, "..", "data", "pre-enable")
fullfnSet = set()
for fn in os.listdir(os.path.join(selfDir, repo, "games-vn")):
    fullfn = os.path.join(preEnableDir, fn + ".new_package")
    with open(fullfn, "w") as f:
        f.write("[main]\n")
        f.write("name = vimproved\n")
        f.write("package = games-vn/%s\n" % (fn))
    fullfnSet.add(fullfn)

for fullfn in glob.glob(os.path.join(preEnableDir, "*")):
    if "package = games-vn/" in pathlib.Path(fullfn).read_text() and fullfn not in fullfnSet:
        Util.forceDelete(fullfn)

Util.forceDelete(repoDir)
